﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using System;
using System.Collections.Generic;
using System.Text;

namespace AspNetCore.Browser.Protection
{
    /// <summary>
    /// broswer加密解密处理
    /// </summary>
    public class BrowserProtection : IBrowserProtection
    {
        private IDataProtectionProvider _dataProtectionProvider;
        private SecureDataFormat<string> _dataFormat;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataProtectionProvider"></param>
        public BrowserProtection(IDataProtectionProvider dataProtectionProvider)
        {
            _dataProtectionProvider = dataProtectionProvider;
            var dataProtector = _dataProtectionProvider.CreateProtector(typeof(BrowserProtection).FullName);
            _dataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector);

        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Protect(string data)
        {
            return _dataFormat.Protect(data);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="protectedText"></param>
        /// <returns></returns>
        public string Unprotect(string protectedText)
        {
            try
            {
                if (String.IsNullOrEmpty(protectedText))
                    return string.Empty;
                return _dataFormat.Unprotect(protectedText);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private class StringSerializer : IDataSerializer<string>
        {
            public string Deserialize(byte[] data)
            {
                return Encoding.UTF8.GetString(data);
            }

            public byte[] Serialize(string model)
            {
                return Encoding.UTF8.GetBytes(model);
            }
        }
    }
}
